3 * Implements Special:UserLogin
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
25 * Implements Special:UserLogin
27 * @ingroup SpecialPage
29 class LoginForm
extends SpecialPage
{
34 const WRONG_PLUGIN_PASS
= 3;
40 const CREATE_BLOCKED
= 9;
42 const USER_BLOCKED
= 11;
43 const NEED_TOKEN
= 12;
44 const WRONG_TOKEN
= 13;
46 var $mUsername, $mPassword, $mRetype, $mReturnTo, $mCookieCheck, $mPosted;
47 var $mAction, $mCreateaccount, $mCreateaccountMail;
48 var $mLoginattempt, $mRemember, $mEmail, $mDomain, $mLanguage;
49 var $mSkipCookieCheck, $mReturnToQuery, $mToken, $mStickHTTPS;
50 var $mType, $mReason, $mRealName;
51 var $mAbortLoginErrorMsg = 'login-abort-generic';
52 private $mLoaded = false;
57 private $mOverrideRequest = null;
60 * @param WebRequest $request
62 public function __construct( $request = null ) {
63 parent
::__construct( 'Userlogin' );
65 $this->mOverrideRequest
= $request;
72 global $wgAuth, $wgHiddenPrefs, $wgEnableEmail;
74 if ( $this->mLoaded
) {
77 $this->mLoaded
= true;
79 if ( $this->mOverrideRequest
=== null ) {
80 $request = $this->getRequest();
82 $request = $this->mOverrideRequest
;
85 $this->mType
= $request->getText( 'type' );
86 $this->mUsername
= $request->getText( 'wpName' );
87 $this->mPassword
= $request->getText( 'wpPassword' );
88 $this->mRetype
= $request->getText( 'wpRetype' );
89 $this->mDomain
= $request->getText( 'wpDomain' );
90 $this->mReason
= $request->getText( 'wpReason' );
91 $this->mCookieCheck
= $request->getVal( 'wpCookieCheck' );
92 $this->mPosted
= $request->wasPosted();
93 $this->mCreateaccountMail
= $request->getCheck( 'wpCreateaccountMail' )
95 $this->mCreateaccount
= $request->getCheck( 'wpCreateaccount' ) && !$this->mCreateaccountMail
;
96 $this->mLoginattempt
= $request->getCheck( 'wpLoginattempt' );
97 $this->mAction
= $request->getVal( 'action' );
98 $this->mRemember
= $request->getCheck( 'wpRemember' );
99 $this->mStickHTTPS
= $request->getCheck( 'wpStickHTTPS' );
100 $this->mLanguage
= $request->getText( 'uselang' );
101 $this->mSkipCookieCheck
= $request->getCheck( 'wpSkipCookieCheck' );
102 $this->mToken
= ( $this->mType
== 'signup' ) ?
$request->getVal( 'wpCreateaccountToken' ) : $request->getVal( 'wpLoginToken' );
103 $this->mReturnTo
= $request->getVal( 'returnto', '' );
104 $this->mReturnToQuery
= $request->getVal( 'returntoquery', '' );
106 if( $wgEnableEmail ) {
107 $this->mEmail
= $request->getText( 'wpEmail' );
111 if( !in_array( 'realname', $wgHiddenPrefs ) ) {
112 $this->mRealName
= $request->getText( 'wpRealName' );
114 $this->mRealName
= '';
117 if( !$wgAuth->validDomain( $this->mDomain
) ) {
118 $this->mDomain
= $wgAuth->getDomain();
120 $wgAuth->setDomain( $this->mDomain
);
122 # 1. When switching accounts, it sucks to get automatically logged out
123 # 2. Do not return to PasswordReset after a successful password change
124 # but goto Wiki start page (Main_Page) instead ( bug 33997 )
125 $returnToTitle = Title
::newFromText( $this->mReturnTo
);
126 if( is_object( $returnToTitle ) && (
127 $returnToTitle->isSpecial( 'Userlogout' )
128 ||
$returnToTitle->isSpecial( 'PasswordReset' ) ) ) {
129 $this->mReturnTo
= '';
130 $this->mReturnToQuery
= '';
134 function getDescription() {
135 return $this->msg( $this->getUser()->isAllowed( 'createaccount' ) ?
136 'userlogin' : 'userloginnocreate' )->text();
139 public function execute( $par ) {
140 if ( session_id() == '' ) {
147 global $wgSecureLogin;
149 $this->mType
!== 'signup' &&
151 WebRequest
::detectProtocol() !== 'https'
153 $title = $this->getFullTitle();
155 'returnto' => $this->mReturnTo
,
156 'returntoquery' => $this->mReturnToQuery
,
157 'wpStickHTTPS' => $this->mStickHTTPS
159 $url = $title->getFullURL( $query, false, PROTO_HTTPS
);
160 $this->getOutput()->redirect( $url );
164 if ( $par == 'signup' ) { # Check for [[Special:Userlogin/signup]]
165 $this->mType
= 'signup';
168 if ( !is_null( $this->mCookieCheck
) ) {
169 $this->onCookieRedirectCheck( $this->mCookieCheck
);
171 } elseif( $this->mPosted
) {
172 if( $this->mCreateaccount
) {
173 $this->addNewAccount();
175 } elseif ( $this->mCreateaccountMail
) {
176 $this->addNewAccountMailPassword();
178 } elseif ( ( 'submitlogin' == $this->mAction
) ||
$this->mLoginattempt
) {
179 $this->processLogin();
183 $this->mainLoginForm( '' );
189 function addNewAccountMailPassword() {
190 if ( $this->mEmail
== '' ) {
191 $this->mainLoginForm( $this->msg( 'noemailcreate' )->escaped() );
195 $status = $this->addNewaccountInternal();
196 if( !$status->isGood() ) {
197 $error = $this->getOutput()->parse( $status->getWikiText() );
198 $this->mainLoginForm( $error );
202 $u = $status->getValue();
204 // Wipe the initial password and mail a temporary one
205 $u->setPassword( null );
207 $result = $this->mailPasswordInternal( $u, false, 'createaccount-title', 'createaccount-text' );
209 wfRunHooks( 'AddNewAccount', array( $u, true ) );
210 $u->addNewUserLogEntry( 'byemail', $this->mReason
);
212 $out = $this->getOutput();
213 $out->setPageTitle( $this->msg( 'accmailtitle' ) );
215 if( !$result->isGood() ) {
216 $this->mainLoginForm( $this->msg( 'mailerror', $result->getWikiText() )->text() );
218 $out->addWikiMsg( 'accmailtext', $u->getName(), $u->getEmail() );
219 $this->executeReturnTo( 'success' );
227 function addNewAccount() {
228 global $wgContLang, $wgUser, $wgEmailAuthentication, $wgLoginLanguageSelector;
230 # Create the account and abort if there's a problem doing so
231 $status = $this->addNewAccountInternal();
232 if( !$status->isGood() ) {
233 $error = $this->getOutput()->parse( $status->getWikiText() );
234 $this->mainLoginForm( $error );
238 $u = $status->getValue();
240 # Only save preferences if the user is not creating an account for someone else.
241 if ( $this->getUser()->isAnon() ) {
242 # If we showed up language selection links, and one was in use, be
243 # smart (and sensible) and save that language as the user's preference
244 if( $wgLoginLanguageSelector && $this->mLanguage
) {
245 $u->setOption( 'language', $this->mLanguage
);
248 # Otherwise the user's language preference defaults to $wgContLang,
249 # but it may be better to set it to their preferred $wgContLang variant,
250 # based on browser preferences or URL parameters.
251 $u->setOption( 'language', $wgContLang->getPreferredVariant() );
253 if ( $wgContLang->hasVariants() ) {
254 $u->setOption( 'variant', $wgContLang->getPreferredVariant() );
258 $out = $this->getOutput();
260 # Send out an email authentication message if needed
261 if( $wgEmailAuthentication && Sanitizer
::validateEmail( $u->getEmail() ) ) {
262 $status = $u->sendConfirmationMail();
263 if( $status->isGood() ) {
264 $out->addWikiMsg( 'confirmemail_oncreate' );
266 $out->addWikiText( $status->getWikiText( 'confirmemail_sendfailed' ) );
270 # Save settings (including confirmation token)
273 # If not logged in, assume the new account as the current one and set
274 # session cookies then show a "welcome" message or a "need cookies"
276 if( $this->getUser()->isAnon() ) {
279 // This should set it for OutputPage and the Skin
280 // which is needed or the personal links will be
282 $this->getContext()->setUser( $u );
283 wfRunHooks( 'AddNewAccount', array( $u, false ) );
284 $u->addNewUserLogEntry( 'create' );
285 if( $this->hasSessionCookie() ) {
286 $this->successfulCreation();
288 $this->cookieRedirectCheck( 'new' );
291 # Confirm that the account was created
292 $out->setPageTitle( $this->msg( 'accountcreated' ) );
293 $out->addWikiMsg( 'accountcreatedtext', $u->getName() );
294 $out->addReturnTo( $this->getTitle() );
295 wfRunHooks( 'AddNewAccount', array( $u, false ) );
296 $u->addNewUserLogEntry( 'create2', $this->mReason
);
302 * Make a new user account using the loaded data.
304 * @throws PermissionsError|ReadOnlyError
307 public function addNewAccountInternal() {
308 global $wgAuth, $wgMemc, $wgAccountCreationThrottle,
309 $wgMinimalPasswordLength, $wgEmailConfirmToEdit;
311 // If the user passes an invalid domain, something is fishy
312 if( !$wgAuth->validDomain( $this->mDomain
) ) {
313 return Status
::newFatal( 'wrongpassword' );
316 // If we are not allowing users to login locally, we should be checking
317 // to see if the user is actually able to authenticate to the authenti-
318 // cation server before they create an account (otherwise, they can
319 // create a local account and login as any domain user). We only need
320 // to check this for domains that aren't local.
321 if( 'local' != $this->mDomain
&& $this->mDomain
!= '' ) {
323 !$wgAuth->canCreateAccounts() &&
325 !$wgAuth->userExists( $this->mUsername
) ||
326 !$wgAuth->authenticate( $this->mUsername
, $this->mPassword
)
329 return Status
::newFatal( 'wrongpassword' );
333 if ( wfReadOnly() ) {
334 throw new ReadOnlyError
;
337 # Request forgery checks.
338 if ( !self
::getCreateaccountToken() ) {
339 self
::setCreateaccountToken();
340 return Status
::newFatal( 'nocookiesfornew' );
343 # The user didn't pass a createaccount token
344 if ( !$this->mToken
) {
345 return Status
::newFatal( 'sessionfailure' );
348 # Validate the createaccount token
349 if ( $this->mToken
!== self
::getCreateaccountToken() ) {
350 return Status
::newFatal( 'sessionfailure' );
354 $currentUser = $this->getUser();
355 $creationBlock = $currentUser->isBlockedFromCreateAccount();
356 if ( !$currentUser->isAllowed( 'createaccount' ) ) {
357 throw new PermissionsError( 'createaccount' );
358 } elseif ( $creationBlock instanceof Block
) {
359 // Throws an ErrorPageError.
360 $this->userBlockedMessage( $creationBlock );
361 // This should never be reached.
365 # Include checks that will include GlobalBlocking (Bug 38333)
366 $permErrors = $this->getTitle()->getUserPermissionsErrors( 'createaccount', $currentUser, true );
367 if ( count( $permErrors ) ) {
368 throw new PermissionsError( 'createaccount', $permErrors );
371 $ip = $this->getRequest()->getIP();
372 if ( $currentUser->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
373 return Status
::newFatal( 'sorbs_create_account_reason' );
376 # Now create a dummy user ($u) and check if it is valid
377 $name = trim( $this->mUsername
);
378 $u = User
::newFromName( $name, 'creatable' );
379 if ( !is_object( $u ) ) {
380 return Status
::newFatal( 'noname' );
381 } elseif ( 0 != $u->idForName() ) {
382 return Status
::newFatal( 'userexists' );
385 if ( $this->mCreateaccountMail
) {
386 # do not force a password for account creation by email
387 # set invalid password, it will be replaced later by a random generated password
388 $this->mPassword
= null;
390 if ( $this->mPassword
!== $this->mRetype
) {
391 return Status
::newFatal( 'badretype' );
394 # check for minimal password length
395 $valid = $u->getPasswordValidity( $this->mPassword
);
396 if ( $valid !== true ) {
397 if ( !is_array( $valid ) ) {
398 $valid = array( $valid, $wgMinimalPasswordLength );
400 return call_user_func_array( 'Status::newFatal', $valid );
404 # if you need a confirmed email address to edit, then obviously you
405 # need an email address.
406 if ( $wgEmailConfirmToEdit && strval( $this->mEmail
) === '' ) {
407 return Status
::newFatal( 'noemailtitle' );
410 if ( strval( $this->mEmail
) !== '' && !Sanitizer
::validateEmail( $this->mEmail
) ) {
411 return Status
::newFatal( 'invalidemailaddress' );
414 # Set some additional data so the AbortNewAccount hook can be used for
415 # more than just username validation
416 $u->setEmail( $this->mEmail
);
417 $u->setRealName( $this->mRealName
);
420 if( !wfRunHooks( 'AbortNewAccount', array( $u, &$abortError ) ) ) {
421 // Hook point to add extra creation throttles and blocks
422 wfDebug( "LoginForm::addNewAccountInternal: a hook blocked creation\n" );
423 return Status
::newFatal( new RawMessage( $abortError ) );
426 // Hook point to check for exempt from account creation throttle
427 if ( !wfRunHooks( 'ExemptFromAccountCreationThrottle', array( $ip ) ) ) {
428 wfDebug( "LoginForm::exemptFromAccountCreationThrottle: a hook allowed account creation w/o throttle\n" );
430 if ( ( $wgAccountCreationThrottle && $currentUser->isPingLimitable() ) ) {
431 $key = wfMemcKey( 'acctcreate', 'ip', $ip );
432 $value = $wgMemc->get( $key );
434 $wgMemc->set( $key, 0, 86400 );
436 if ( $value >= $wgAccountCreationThrottle ) {
437 return Status
::newFatal( 'acct_creation_throttle_hit', $wgAccountCreationThrottle );
439 $wgMemc->incr( $key );
443 if( !$wgAuth->addUser( $u, $this->mPassword
, $this->mEmail
, $this->mRealName
) ) {
444 return Status
::newFatal( 'externaldberror' );
447 self
::clearCreateaccountToken();
448 return $this->initUser( $u, false );
452 * Actually add a user to the database.
453 * Give it a User object that has been initialised with a name.
455 * @param $u User object.
456 * @param $autocreate boolean -- true if this is an autocreation via auth plugin
457 * @return Status object, with the User object in the value member on success
460 function initUser( $u, $autocreate ) {
463 $status = $u->addToDatabase();
464 if ( !$status->isOK() ) {
468 if ( $wgAuth->allowPasswordChange() ) {
469 $u->setPassword( $this->mPassword
);
472 $u->setEmail( $this->mEmail
);
473 $u->setRealName( $this->mRealName
);
476 $wgAuth->initUser( $u, $autocreate );
478 $u->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
482 DeferredUpdates
::addUpdate( new SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
484 return Status
::newGood( $u );
488 * Internally authenticate the login request.
490 * This may create a local account as a side effect if the
491 * authentication plugin allows transparent local account
495 public function authenticateUserData() {
496 global $wgUser, $wgAuth;
500 if ( $this->mUsername
== '' ) {
501 return self
::NO_NAME
;
504 // We require a login token to prevent login CSRF
505 // Handle part of this before incrementing the throttle so
506 // token-less login attempts don't count towards the throttle
507 // but wrong-token attempts do.
509 // If the user doesn't have a login token yet, set one.
510 if ( !self
::getLoginToken() ) {
511 self
::setLoginToken();
512 return self
::NEED_TOKEN
;
514 // If the user didn't pass a login token, tell them we need one
515 if ( !$this->mToken
) {
516 return self
::NEED_TOKEN
;
519 $throttleCount = self
::incLoginThrottle( $this->mUsername
);
520 if ( $throttleCount === true ) {
521 return self
::THROTTLED
;
524 // Validate the login token
525 if ( $this->mToken
!== self
::getLoginToken() ) {
526 return self
::WRONG_TOKEN
;
529 // Load the current user now, and check to see if we're logging in as
530 // the same name. This is necessary because loading the current user
531 // (say by calling getName()) calls the UserLoadFromSession hook, which
532 // potentially creates the user in the database. Until we load $wgUser,
533 // checking for user existence using User::newFromName($name)->getId() below
534 // will effectively be using stale data.
535 if ( $this->getUser()->getName() === $this->mUsername
) {
536 wfDebug( __METHOD__
. ": already logged in as {$this->mUsername}\n" );
537 return self
::SUCCESS
;
540 $u = User
::newFromName( $this->mUsername
);
541 if( !( $u instanceof User
) ||
!User
::isUsableName( $u->getName() ) ) {
542 return self
::ILLEGAL
;
545 $isAutoCreated = false;
546 if ( $u->getID() == 0 ) {
547 $status = $this->attemptAutoCreate( $u );
548 if ( $status !== self
::SUCCESS
) {
551 $isAutoCreated = true;
557 // Give general extensions, such as a captcha, a chance to abort logins
558 $abort = self
::ABORTED
;
559 if( !wfRunHooks( 'AbortLogin', array( $u, $this->mPassword
, &$abort, &$this->mAbortLoginErrorMsg
) ) ) {
563 global $wgBlockDisablesLogin;
564 if ( !$u->checkPassword( $this->mPassword
) ) {
565 if( $u->checkTemporaryPassword( $this->mPassword
) ) {
566 // The e-mailed temporary password should not be used for actu-
567 // al logins; that's a very sloppy habit, and insecure if an
568 // attacker has a few seconds to click "search" on someone's o-
571 // Allow it to be used only to reset the password a single time
572 // to a new value, which won't be in the user's e-mail ar-
575 // For backwards compatibility, we'll still recognize it at the
576 // login form to minimize surprises for people who have been
577 // logging in with a temporary password for some time.
579 // As a side-effect, we can authenticate the user's e-mail ad-
580 // dress if it's not already done, since the temporary password
581 // was sent via e-mail.
582 if( !$u->isEmailConfirmed() ) {
587 // At this point we just return an appropriate code/ indicating
588 // that the UI should show a password reset form; bot inter-
589 // faces etc will probably just fail cleanly here.
590 $retval = self
::RESET_PASS
;
592 $retval = ( $this->mPassword
== '' ) ? self
::EMPTY_PASS
: self
::WRONG_PASS
;
594 } elseif ( $wgBlockDisablesLogin && $u->isBlocked() ) {
595 // If we've enabled it, make it so that a blocked user cannot login
596 $retval = self
::USER_BLOCKED
;
598 $wgAuth->updateUser( $u );
600 // This should set it for OutputPage and the Skin
601 // which is needed or the personal links will be
603 $this->getContext()->setUser( $u );
605 // Please reset throttle for successful logins, thanks!
606 if ( $throttleCount ) {
607 self
::clearLoginThrottle( $this->mUsername
);
610 if ( $isAutoCreated ) {
611 // Must be run after $wgUser is set, for correct new user log
612 wfRunHooks( 'AuthPluginAutoCreate', array( $u ) );
615 $retval = self
::SUCCESS
;
617 wfRunHooks( 'LoginAuthenticateAudit', array( $u, $this->mPassword
, $retval ) );
622 * Increment the login attempt throttle hit count for the (username,current IP)
623 * tuple unless the throttle was already reached.
624 * @param string $username The user name
625 * @return Bool|Integer The integer hit count or True if it is already at the limit
627 public static function incLoginThrottle( $username ) {
628 global $wgPasswordAttemptThrottle, $wgMemc, $wgRequest;
629 $username = trim( $username ); // sanity
632 if ( is_array( $wgPasswordAttemptThrottle ) ) {
633 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
634 $count = $wgPasswordAttemptThrottle['count'];
635 $period = $wgPasswordAttemptThrottle['seconds'];
637 $throttleCount = $wgMemc->get( $throttleKey );
638 if ( !$throttleCount ) {
639 $wgMemc->add( $throttleKey, 1, $period ); // start counter
640 } elseif ( $throttleCount < $count ) {
641 $wgMemc->incr( $throttleKey );
642 } elseif ( $throttleCount >= $count ) {
647 return $throttleCount;
651 * Clear the login attempt throttle hit count for the (username,current IP) tuple.
652 * @param string $username The user name
655 public static function clearLoginThrottle( $username ) {
656 global $wgMemc, $wgRequest;
657 $username = trim( $username ); // sanity
659 $throttleKey = wfMemcKey( 'password-throttle', $wgRequest->getIP(), md5( $username ) );
660 $wgMemc->delete( $throttleKey );
664 * Attempt to automatically create a user on login. Only succeeds if there
665 * is an external authentication method which allows it.
669 * @return integer Status code
671 function attemptAutoCreate( $user ) {
674 if ( $this->getUser()->isBlockedFromCreateAccount() ) {
675 wfDebug( __METHOD__
. ": user is blocked from account creation\n" );
676 return self
::CREATE_BLOCKED
;
678 if ( !$wgAuth->autoCreate() ) {
679 return self
::NOT_EXISTS
;
681 if ( !$wgAuth->userExists( $user->getName() ) ) {
682 wfDebug( __METHOD__
. ": user does not exist\n" );
683 return self
::NOT_EXISTS
;
685 if ( !$wgAuth->authenticate( $user->getName(), $this->mPassword
) ) {
686 wfDebug( __METHOD__
. ": \$wgAuth->authenticate() returned false, aborting\n" );
687 return self
::WRONG_PLUGIN_PASS
;
691 if( !wfRunHooks( 'AbortAutoAccount', array( $user, &$abortError ) ) ) {
692 // Hook point to add extra creation throttles and blocks
693 wfDebug( "LoginForm::attemptAutoCreate: a hook blocked creation: $abortError\n" );
694 $this->mAbortLoginErrorMsg
= $abortError;
695 return self
::ABORTED
;
698 wfDebug( __METHOD__
. ": creating account\n" );
699 $status = $this->initUser( $user, true );
701 if ( !$status->isOK() ) {
702 $errors = $status->getErrorsByType( 'error' );
703 $this->mAbortLoginErrorMsg
= $errors[0]['message'];
704 return self
::ABORTED
;
707 return self
::SUCCESS
;
710 function processLogin() {
711 global $wgMemc, $wgLang, $wgSecureLogin;
713 switch ( $this->authenticateUserData() ) {
715 # We've verified now, update the real record
716 $user = $this->getUser();
717 if( (bool)$this->mRemember
!= $user->getBoolOption( 'rememberpassword' ) ) {
718 $user->setOption( 'rememberpassword', $this->mRemember ?
1 : 0 );
719 $user->saveSettings();
721 $user->invalidateCache();
724 if( $wgSecureLogin && !$this->mStickHTTPS
) {
725 $user->setCookies( null, false );
729 self
::clearLoginToken();
731 // Reset the throttle
732 $request = $this->getRequest();
733 $key = wfMemcKey( 'password-throttle', $request->getIP(), md5( $this->mUsername
) );
734 $wgMemc->delete( $key );
736 if( $this->hasSessionCookie() ||
$this->mSkipCookieCheck
) {
737 /* Replace the language object to provide user interface in
738 * correct language immediately on this first page load.
740 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
741 $userLang = Language
::factory( $code );
743 $this->getContext()->setLanguage( $userLang );
744 // Reset SessionID on Successful login (bug 40995)
745 $this->renewSessionId();
746 $this->successfulLogin();
748 $this->cookieRedirectCheck( 'login' );
752 case self
::NEED_TOKEN
:
753 $this->mainLoginForm( $this->msg( 'nocookiesforlogin' )->parse() );
755 case self
::WRONG_TOKEN
:
756 $this->mainLoginForm( $this->msg( 'sessionfailure' )->text() );
760 $this->mainLoginForm( $this->msg( 'noname' )->text() );
762 case self
::WRONG_PLUGIN_PASS
:
763 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
765 case self
::NOT_EXISTS
:
766 if( $this->getUser()->isAllowed( 'createaccount' ) ) {
767 $this->mainLoginForm( $this->msg( 'nosuchuser',
768 wfEscapeWikiText( $this->mUsername
) )->parse() );
770 $this->mainLoginForm( $this->msg( 'nosuchusershort',
771 wfEscapeWikiText( $this->mUsername
) )->text() );
774 case self
::WRONG_PASS
:
775 $this->mainLoginForm( $this->msg( 'wrongpassword' )->text() );
777 case self
::EMPTY_PASS
:
778 $this->mainLoginForm( $this->msg( 'wrongpasswordempty' )->text() );
780 case self
::RESET_PASS
:
781 $this->resetLoginForm( $this->msg( 'resetpass_announce' )->text() );
783 case self
::CREATE_BLOCKED
:
784 $this->userBlockedMessage( $this->getUser()->mBlock
);
786 case self
::THROTTLED
:
787 $this->mainLoginForm( $this->msg( 'login-throttled' )->text() );
789 case self
::USER_BLOCKED
:
790 $this->mainLoginForm( $this->msg( 'login-userblocked',
791 $this->mUsername
)->escaped() );
794 $this->mainLoginForm( $this->msg( $this->mAbortLoginErrorMsg
)->text() );
797 throw new MWException( 'Unhandled case value' );
802 * @param $error string
804 function resetLoginForm( $error ) {
805 $this->getOutput()->addHTML( Xml
::element( 'p', array( 'class' => 'error' ), $error ) );
806 $reset = new SpecialChangePassword();
807 $reset->setContext( $this->getContext() );
808 $reset->execute( null );
812 * @param $u User object
813 * @param $throttle Boolean
814 * @param string $emailTitle message name of email title
815 * @param string $emailText message name of email text
816 * @return Status object
818 function mailPasswordInternal( $u, $throttle = true, $emailTitle = 'passwordremindertitle', $emailText = 'passwordremindertext' ) {
819 global $wgCanonicalServer, $wgScript, $wgNewPasswordExpiry;
821 if ( $u->getEmail() == '' ) {
822 return Status
::newFatal( 'noemail', $u->getName() );
824 $ip = $this->getRequest()->getIP();
826 return Status
::newFatal( 'badipaddress' );
829 $currentUser = $this->getUser();
830 wfRunHooks( 'User::mailPasswordInternal', array( &$currentUser, &$ip, &$u ) );
832 $np = $u->randomPassword();
833 $u->setNewpassword( $np, $throttle );
835 $userLanguage = $u->getOption( 'language' );
836 $m = $this->msg( $emailText, $ip, $u->getName(), $np, '<' . $wgCanonicalServer . $wgScript . '>',
837 round( $wgNewPasswordExpiry / 86400 ) )->inLanguage( $userLanguage )->text();
838 $result = $u->sendMail( $this->msg( $emailTitle )->inLanguage( $userLanguage )->text(), $m );
844 * Run any hooks registered for logins, then HTTP redirect to
845 * $this->mReturnTo (or Main Page if that's undefined). Formerly we had a
846 * nice message here, but that's really not as useful as just being sent to
847 * wherever you logged in from. It should be clear that the action was
848 * successful, given the lack of error messages plus the appearance of your
849 * name in the upper right.
853 function successfulLogin() {
854 # Run any hooks; display injected HTML if any, else redirect
855 $currentUser = $this->getUser();
857 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
859 if( $injected_html !== '' ) {
860 $this->displaySuccessfulAction( $this->msg( 'loginsuccesstitle' ),
861 'loginsuccess', $injected_html );
863 $this->executeReturnTo( 'successredirect' );
868 * Run any hooks registered for logins, then display a message welcoming
873 function successfulCreation() {
874 # Run any hooks; display injected HTML
875 $currentUser = $this->getUser();
877 $welcome_creation_msg = 'welcomecreation-msg';
879 wfRunHooks( 'UserLoginComplete', array( &$currentUser, &$injected_html ) );
882 * Let any extensions change what message is shown.
883 * @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforeWelcomeCreation
886 wfRunHooks( 'BeforeWelcomeCreation', array( &$welcome_creation_msg, &$injected_html ) );
888 $this->displaySuccessfulAction( $this->msg( 'welcomeuser', $this->getUser()->getName() ),
889 $welcome_creation_msg, $injected_html );
893 * Display an "successful action" page.
895 * @param string|Message $title page's title
896 * @param $msgname string
897 * @param $injected_html string
899 private function displaySuccessfulAction( $title, $msgname, $injected_html ) {
900 $out = $this->getOutput();
901 $out->setPageTitle( $title );
903 $out->addWikiMsg( $msgname, wfEscapeWikiText( $this->getUser()->getName() ) );
906 $out->addHTML( $injected_html );
908 $this->executeReturnTo( 'success' );
912 * Output a message that informs the user that they cannot create an account because
913 * there is a block on them or their IP which prevents account creation. Note that
914 * User::isBlockedFromCreateAccount(), which gets this block, ignores the 'hardblock'
915 * setting on blocks (bug 13611).
916 * @param $block Block the block causing this error
917 * @throws ErrorPageError
919 function userBlockedMessage( Block
$block ) {
920 # Let's be nice about this, it's likely that this feature will be used
921 # for blocking large numbers of innocent people, e.g. range blocks on
922 # schools. Don't blame it on the user. There's a small chance that it
923 # really is the user's fault, i.e. the username is blocked and they
924 # haven't bothered to log out before trying to create an account to
925 # evade it, but we'll leave that to their guilty conscience to figure
927 throw new ErrorPageError(
928 'cantcreateaccounttitle',
929 'cantcreateaccount-text',
932 $block->mReason ?
$block->mReason
: $this->msg( 'blockednoreason' )->text(),
939 * Add a "return to" link or redirect to it.
941 * @param $type string, one of the following:
942 * - error: display a return to link ignoring $wgRedirectOnLogin
943 * - success: display a return to link using $wgRedirectOnLogin if needed
944 * - successredirect: send an HTTP redirect using $wgRedirectOnLogin if needed
946 private function executeReturnTo( $type ) {
947 global $wgRedirectOnLogin, $wgSecureLogin;
949 if ( $type != 'error' && $wgRedirectOnLogin !== null ) {
950 $returnTo = $wgRedirectOnLogin;
951 $returnToQuery = array();
953 $returnTo = $this->mReturnTo
;
954 $returnToQuery = wfCgiToArray( $this->mReturnToQuery
);
957 $returnToTitle = Title
::newFromText( $returnTo );
958 if ( !$returnToTitle ) {
959 $returnToTitle = Title
::newMainPage();
962 if ( $wgSecureLogin && !$this->mStickHTTPS
) {
963 $options = array( 'http' );
965 } elseif( $wgSecureLogin ) {
966 $options = array( 'https' );
967 $proto = PROTO_HTTPS
;
970 $proto = PROTO_RELATIVE
;
973 if ( $type == 'successredirect' ) {
974 $redirectUrl = $returnToTitle->getFullURL( $returnToQuery, false, $proto );
975 $this->getOutput()->redirect( $redirectUrl );
977 $this->getOutput()->addReturnTo( $returnToTitle, $returnToQuery, null, $options );
984 function mainLoginForm( $msg, $msgtype = 'error' ) {
985 global $wgEnableEmail, $wgEnableUserEmail;
986 global $wgHiddenPrefs, $wgLoginLanguageSelector;
987 global $wgAuth, $wgEmailConfirmToEdit, $wgCookieExpiration;
988 global $wgSecureLogin, $wgSecureLoginDefaultHTTPS, $wgPasswordResetRoutes;
990 $titleObj = $this->getTitle();
991 $user = $this->getUser();
993 if ( $this->mType
== 'signup' ) {
994 // Block signup here if in readonly. Keeps user from
995 // going through the process (filling out data, etc)
996 // and being informed later.
997 $permErrors = $titleObj->getUserPermissionsErrors( 'createaccount', $user, true );
998 if ( count( $permErrors ) ) {
999 throw new PermissionsError( 'createaccount', $permErrors );
1000 } elseif ( $user->isBlockedFromCreateAccount() ) {
1001 $this->userBlockedMessage( $user->isBlockedFromCreateAccount() );
1003 } elseif ( wfReadOnly() ) {
1004 throw new ReadOnlyError
;
1008 // Pre-fill username (if not creating an account, bug 44775).
1009 if ( $this->mUsername
== '' && $this->mType
!= 'signup' ) {
1010 if ( $user->isLoggedIn() ) {
1011 $this->mUsername
= $user->getName();
1013 $this->mUsername
= $this->getRequest()->getCookie( 'UserName' );
1017 if ( $this->mType
== 'signup' ) {
1018 $template = new UsercreateTemplate();
1019 $q = 'action=submitlogin&type=signup';
1020 $linkq = 'type=login';
1021 $linkmsg = 'gotaccount';
1022 $this->getOutput()->addModules( 'mediawiki.special.userlogin.signup' );
1024 $template = new UserloginTemplate();
1025 $q = 'action=submitlogin&type=login';
1026 $linkq = 'type=signup';
1027 $linkmsg = 'nologin';
1030 if ( $this->mReturnTo
!== '' ) {
1031 $returnto = '&returnto=' . wfUrlencode( $this->mReturnTo
);
1032 if ( $this->mReturnToQuery
!== '' ) {
1033 $returnto .= '&returntoquery=' .
1034 wfUrlencode( $this->mReturnToQuery
);
1037 $linkq .= $returnto;
1040 # Don't show a "create account" link if the user can't
1041 if( $this->showCreateOrLoginLink( $user ) ) {
1042 # Pass any language selection on to the mode switch link
1043 if( $wgLoginLanguageSelector && $this->mLanguage
) {
1044 $linkq .= '&uselang=' . $this->mLanguage
;
1046 $link = Html
::element( 'a', array( 'href' => $titleObj->getLocalURL( $linkq ) ),
1047 $this->msg( $linkmsg . 'link' )->text() ); # Calling either 'gotaccountlink' or 'nologinlink'
1049 $template->set( 'link', $this->msg( $linkmsg )->rawParams( $link )->parse() );
1051 $template->set( 'link', '' );
1054 // Decide if we default stickHTTPS on
1055 if ( $wgSecureLoginDefaultHTTPS && $this->mAction
!= 'submitlogin' && !$this->mLoginattempt
) {
1056 $this->mStickHTTPS
= true;
1059 $resetLink = $this->mType
== 'signup'
1061 : is_array( $wgPasswordResetRoutes ) && in_array( true, array_values( $wgPasswordResetRoutes ) );
1063 $template->set( 'header', '' );
1064 $template->set( 'name', $this->mUsername
);
1065 $template->set( 'password', $this->mPassword
);
1066 $template->set( 'retype', $this->mRetype
);
1067 $template->set( 'createemailset', $this->mCreateaccountMail
);
1068 $template->set( 'email', $this->mEmail
);
1069 $template->set( 'realname', $this->mRealName
);
1070 $template->set( 'domain', $this->mDomain
);
1071 $template->set( 'reason', $this->mReason
);
1073 $template->set( 'action', $titleObj->getLocalURL( $q ) );
1074 $template->set( 'message', $msg );
1075 $template->set( 'messagetype', $msgtype );
1076 $template->set( 'createemail', $wgEnableEmail && $user->isLoggedIn() );
1077 $template->set( 'userealname', !in_array( 'realname', $wgHiddenPrefs ) );
1078 $template->set( 'useemail', $wgEnableEmail );
1079 $template->set( 'emailrequired', $wgEmailConfirmToEdit );
1080 $template->set( 'emailothers', $wgEnableUserEmail );
1081 $template->set( 'canreset', $wgAuth->allowPasswordChange() );
1082 $template->set( 'resetlink', $resetLink );
1083 $template->set( 'canremember', ( $wgCookieExpiration > 0 ) );
1084 $template->set( 'usereason', $user->isLoggedIn() );
1085 $template->set( 'remember', $user->getOption( 'rememberpassword' ) ||
$this->mRemember
);
1086 $template->set( 'cansecurelogin', ( $wgSecureLogin === true ) );
1087 $template->set( 'stickHTTPS', $this->mStickHTTPS
);
1089 if ( $this->mType
== 'signup' ) {
1090 if ( !self
::getCreateaccountToken() ) {
1091 self
::setCreateaccountToken();
1093 $template->set( 'token', self
::getCreateaccountToken() );
1095 if ( !self
::getLoginToken() ) {
1096 self
::setLoginToken();
1098 $template->set( 'token', self
::getLoginToken() );
1101 # Prepare language selection links as needed
1102 if( $wgLoginLanguageSelector ) {
1103 $template->set( 'languages', $this->makeLanguageSelector() );
1104 if( $this->mLanguage
) {
1105 $template->set( 'uselang', $this->mLanguage
);
1109 // Use loginend-https for HTTPS requests if it's not blank, loginend otherwise
1110 // Ditto for signupend
1111 $usingHTTPS = WebRequest
::detectProtocol() == 'https';
1112 $loginendHTTPS = $this->msg( 'loginend-https' );
1113 $signupendHTTPS = $this->msg( 'signupend-https' );
1114 if ( $usingHTTPS && !$loginendHTTPS->isBlank() ) {
1115 $template->set( 'loginend', $loginendHTTPS->parse() );
1117 $template->set( 'loginend', $this->msg( 'loginend' )->parse() );
1119 if ( $usingHTTPS && !$signupendHTTPS->isBlank() ) {
1120 $template->set( 'signupend', $signupendHTTPS->parse() );
1122 $template->set( 'signupend', $this->msg( 'signupend' )->parse() );
1125 // Give authentication and captcha plugins a chance to modify the form
1126 $wgAuth->modifyUITemplate( $template, $this->mType
);
1127 if ( $this->mType
== 'signup' ) {
1128 wfRunHooks( 'UserCreateForm', array( &$template ) );
1130 wfRunHooks( 'UserLoginForm', array( &$template ) );
1133 $out = $this->getOutput();
1134 $out->disallowUserJs(); // just in case...
1135 $out->addTemplate( $template );
1145 function showCreateOrLoginLink( &$user ) {
1146 if( $this->mType
== 'signup' ) {
1148 } elseif( $user->isAllowed( 'createaccount' ) ) {
1156 * Check if a session cookie is present.
1158 * This will not pick up a cookie set during _this_ request, but is meant
1159 * to ensure that the client is returning the cookie which was set on a
1160 * previous pass through the system.
1165 function hasSessionCookie() {
1166 global $wgDisableCookieCheck;
1167 return $wgDisableCookieCheck ?
true : $this->getRequest()->checkSessionCookie();
1171 * Get the login token from the current session
1174 public static function getLoginToken() {
1176 return $wgRequest->getSessionData( 'wsLoginToken' );
1180 * Randomly generate a new login token and attach it to the current session
1182 public static function setLoginToken() {
1184 // Generate a token directly instead of using $user->editToken()
1185 // because the latter reuses $_SESSION['wsEditToken']
1186 $wgRequest->setSessionData( 'wsLoginToken', MWCryptRand
::generateHex( 32 ) );
1190 * Remove any login token attached to the current session
1192 public static function clearLoginToken() {
1194 $wgRequest->setSessionData( 'wsLoginToken', null );
1198 * Get the createaccount token from the current session
1201 public static function getCreateaccountToken() {
1203 return $wgRequest->getSessionData( 'wsCreateaccountToken' );
1207 * Randomly generate a new createaccount token and attach it to the current session
1209 public static function setCreateaccountToken() {
1211 $wgRequest->setSessionData( 'wsCreateaccountToken', MWCryptRand
::generateHex( 32 ) );
1215 * Remove any createaccount token attached to the current session
1217 public static function clearCreateaccountToken() {
1219 $wgRequest->setSessionData( 'wsCreateaccountToken', null );
1223 * Renew the user's session id, using strong entropy
1225 private function renewSessionId() {
1226 global $wgSecureLogin, $wgCookieSecure;
1227 if( $wgSecureLogin && !$this->mStickHTTPS
) {
1228 $wgCookieSecure = false;
1231 // If either we don't trust PHP's entropy, or if we need
1232 // to change cookie settings when logging in because of
1233 // wpStickHTTPS, then change the session ID manually.
1234 $cookieParams = session_get_cookie_params();
1235 if ( wfCheckEntropy() && $wgCookieSecure == $cookieParams['secure'] ) {
1236 session_regenerate_id( false );
1240 wfSetupSession( MWCryptRand
::generateHex( 32 ) );
1248 function cookieRedirectCheck( $type ) {
1249 $titleObj = SpecialPage
::getTitleFor( 'Userlogin' );
1250 $query = array( 'wpCookieCheck' => $type );
1251 if ( $this->mReturnTo
!== '' ) {
1252 $query['returnto'] = $this->mReturnTo
;
1253 $query['returntoquery'] = $this->mReturnToQuery
;
1255 $check = $titleObj->getFullURL( $query );
1257 $this->getOutput()->redirect( $check );
1263 function onCookieRedirectCheck( $type ) {
1264 if ( !$this->hasSessionCookie() ) {
1265 if ( $type == 'new' ) {
1266 $this->mainLoginForm( $this->msg( 'nocookiesnew' )->parse() );
1267 } elseif ( $type == 'login' ) {
1268 $this->mainLoginForm( $this->msg( 'nocookieslogin' )->parse() );
1271 $this->mainLoginForm( $this->msg( 'error' )->text() );
1274 $this->successfulLogin();
1279 * Produce a bar of links which allow the user to select another language
1280 * during login/registration but retain "returnto"
1284 function makeLanguageSelector() {
1285 $msg = $this->msg( 'loginlanguagelinks' )->inContentLanguage();
1286 if( !$msg->isBlank() ) {
1287 $langs = explode( "\n", $msg->text() );
1289 foreach( $langs as $lang ) {
1290 $lang = trim( $lang, '* ' );
1291 $parts = explode( '|', $lang );
1292 if ( count( $parts ) >= 2 ) {
1293 $links[] = $this->makeLanguageSelectorLink( $parts[0], trim( $parts[1] ) );
1296 return count( $links ) > 0 ?
$this->msg( 'loginlanguagelabel' )->rawParams(
1297 $this->getLanguage()->pipeList( $links ) )->escaped() : '';
1304 * Create a language selector link for a particular language
1305 * Links back to this page preserving type and returnto
1307 * @param string $text Link text
1308 * @param string $lang Language code
1311 function makeLanguageSelectorLink( $text, $lang ) {
1312 if( $this->getLanguage()->getCode() == $lang ) {
1313 // no link for currently used language
1314 return htmlspecialchars( $text );
1316 $query = array( 'uselang' => $lang );
1317 if( $this->mType
== 'signup' ) {
1318 $query['type'] = 'signup';
1320 if( $this->mReturnTo
!== '' ) {
1321 $query['returnto'] = $this->mReturnTo
;
1322 $query['returntoquery'] = $this->mReturnToQuery
;
1326 $targetLanguage = Language
::factory( $lang );
1327 $attr['lang'] = $attr['hreflang'] = $targetLanguage->getHtmlCode();
1329 return Linker
::linkKnown(
1331 htmlspecialchars( $text ),
1337 protected function getGroupName() {